# 指定使用bash作为shell
SHELL := D:/msys64/usr/bin/bash.exe

# 项目基本配置
PROJECT     := server
VERSION     := 1.0.0
CXX_STD     := c++20

# 编译器配置
CXX         := g++
LD          := $(CXX)

# 目录结构
SRC_DIR     := src
INC_DIR     := include
BUILD_DIR   := build
BIN_DIR     := bin

# 文件收集
SOURCES     := $(shell find $(SRC_DIR) -type f -name "*.cpp")
OBJECTS     := $(patsubst $(SRC_DIR)/%.cpp,$(BUILD_DIR)/%.o,$(SOURCES))
DEPFILES    := $(OBJECTS:.o=.d)

# 编译选项
# 编译选项
WARNINGS    := -Wall -Wextra -Wpedantic -Werror
INCLUDES    := -I$(INC_DIR) -I"/d/msys64/mingw64/include" -I"/d/msys64/mingw64/include/boost" -I"/d/msys64/mingw64/include/yaml-cpp"
LIBS        := -L"/d/msys64/mingw64/lib" -lboost_system -lboost_log -lboost_filesystem -lboost_thread -lyaml-cpp -lpthread -lws2_32

# 调试/发布模式配置
DEBUG_CFLAGS    := -g3 -O0 -DDEBUG
RELEASE_CFLAGS  := -O3 -DNDEBUG -flto

# 模式选择
ifeq ($(mode), release)
    CXXFLAGS := $(RELEASE_CFLAGS) $(WARNINGS)
else
    mode := debug
    CXXFLAGS := $(DEBUG_CFLAGS) $(WARNINGS)
endif

LDFLAGS     := $(LIBS)

# 禁用内置规则
.SUFFIXES:

# 主要目标
.PHONY: all clean rebuild run help directories

# 默认目标
all: directories $(BIN_DIR)/$(PROJECT)
	@echo "[✓] 构建完成（模式: $(mode)）"

# 创建目录
directories:
	@mkdir -p $(BIN_DIR) $(BUILD_DIR)

# 链接目标
$(BIN_DIR)/$(PROJECT): $(OBJECTS)
	@echo "正在链接: $@"
	@mkdir -p $(BIN_DIR)
	$(LD) $(OBJECTS) -o $@ $(LDFLAGS)
	@echo "链接完成"
	@ls -la $(BIN_DIR)/

# 编译规则 - 使用明确的模式
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp
	@echo "编译: $<"
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) $(INCLUDES) -MMD -MP -c $< -o $@

# 包含依赖文件
-include $(DEPFILES)

# 清理
clean:
	@rm -rf $(BUILD_DIR) $(BIN_DIR)
	@echo "[✓] 清理完成"

# 重新构建
rebuild: clean all

# 运行
run: all
	@$(BIN_DIR)/$(PROJECT)

# 帮助
help:
	@echo "用法: make [目标] [mode=debug|release]"
	@echo ""
	@echo "目标:"
	@echo "  all       构建项目（默认）"
	@echo "  clean     清理构建产物"
	@echo "  rebuild   清理并重新构建"
	@echo "  run       构建并运行程序"
	@echo ""
	@echo "模式:"
	@echo "  debug     调试模式（默认）"
	@echo "  release   发布模式（优化）"